﻿using ChuanYe.Core.Utils;
using ChuanYe.CountyFireManagement.Api.Controllers;
using ChuanYe.CountyFireManagement.BLL;
using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using ChuanYe.CountyFireManagement.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ChuanYe.CountyFireManagement.Api
{

    /// <summary>
    /// MQTT
    /// </summary>
    public class MqttHub
    {
        public static void Run() 
        {
            Task.Factory.StartNew(() =>
            {
                MQTT_Fire_Expire_Task();
            });
            Task.Factory.StartNew(() =>
            {
                MQTT_Custom_Message_Task();
            });
        }

        /// <summary>
        /// 火灾过期处置
        /// </summary>
        private static void MQTT_Fire_Expire_Task()
        {
            while (true)
            {
                try
                {
                    lock (fireExpireLock)
                    {
                        foreach (var item in fireexpires)
                        {
                            var nowTime = DateTime.Now;
                            if (nowTime > item.StartTime.AddMinutes(item.Value))
                            {
                                Message message = new Message();
                                message.FireId = item.FireId;
                                message.Type = item.MessageType;
                                message.Content = item.MessageContent;
                                message.SendType = (int)MessageSendType.下级向上级发送;
                                message.IsRead = 0;
                                message.HandleTime = DateTime.Now;
                                message.SendUserId = -1;
                                message.Ip = string.Empty;

                                Record record = new Record();
                                record.FireId = item.FireId;
                                record.HandleTime = DateTime.Now;
                                record.Type = item.RecordType;
                                record.UserId = 0;
                                record.Content = item.MessageContent;
                                record.AddTime = DateTime.Now;
                                record.Ip = string.Empty;
                                record.Applicant = "系统自动";
                                record.CustomData = item.ExpireId.ToString();
                                var status = BLL.MessageBLL.Instance.Add(message,null);
                                if (status != 0)
                                {
                                    status = BLL.RecordBLL.Instance.Add(record, null);
                                    if (status != 0)
                                    {
                                        var content = Newtonsoft.Json.JsonConvert.SerializeObject(item);
                                        var myfireExpireTopic = string.Format(fireExpireTopic, item.FireId);
                                        client.Publish(fireExpireTopic, content, false);
                                    }
                                }
                            }
                        }
                        fireexpires = BLL.FireExpireBLL.Instance.GetUnExpire();
                    }
                    Thread.Sleep(5000);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("MqttHub MQTT_Fire_Expire_Task", ex);
                }

            }
        }

        /// <summary>
        /// 自定义 消息发送未读轮询
        /// </summary>
        private static void MQTT_Custom_Message_Task() 
        {
            while (true) 
            {
                try
                {
                    lock (fireExpireLock)
                    {
                       var list=OtherMessageBLL.Instance.GetByPage(null, null, null, 0, new RequestPageBase() { PageIndex = 1, PageSize = int.MaxValue });
                        foreach (var item in list)
                        {
                            ControllerHelper.SendCustomMessage(item, item.TargetUserId.Value);
                        }
                    }
                    Thread.Sleep(2000);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("MqttHub MQTT_Custom_Message_Task", ex);
                }
            }
        }

        /// <summary>
        /// 火灾过期锁
        /// </summary>
        private static readonly object fireExpireLock = new object();

        /// <summary>
        /// MQTT Client
        /// </summary>
        public static MQClient client = new MQClient("ChuanYe_CFM_TASK");

        /// <summary>
        /// 所有等待过期的火灾
        /// </summary>
        public static List<Fireexpire> fireexpires = new List<Fireexpire>();

        /// <summary>
        /// 首报续报终报过期MQTTT {0}=FireId
        /// </summary>
        private static string fireExpireTopic = "/CFM/FireExpire/{0}";

    }
}
